package com.huitongmaoyi.ai.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;


import java.util.*;

public class AIService {
    // 替换为你的API Key
//    private static final String API_KEY = "sk-636fafef39a64f988bb7ada802ef66d4";
    private static final String OPENAI_API_KEY =  System.getenv("OPENAI_API_KEY");

    static {
        if (OPENAI_API_KEY == null || OPENAI_API_KEY.trim().isEmpty()) {
            throw new IllegalArgumentException("请配置API Key");
        }
    }

    /**
     * 将用户输入映射到数据库字段值（如国家、行业）
     */
    public String mapToDatabaseValue(String prompt) {
        try {
            GenerationParam param = GenerationParam.builder()
                    .model("qwen-turbo")  // 确保使用免费且无门槛的模型
                    .apiKey(OPENAI_API_KEY)
                    .messages(Collections.singletonList(
                            Message.builder()
                                    .role(Role.USER.getValue())
                                    .content(prompt)
                                    .build()
                    ))
                    .build();

            Generation generation = new Generation();
            GenerationResult result = generation.call(param);

            // 多层级容错，即使AI返回空也不崩溃
            if (result == null
                    || result.getOutput() == null
                    || result.getOutput().getChoices() == null
                    || result.getOutput().getChoices().isEmpty()
                    || result.getOutput().getChoices().get(0).getMessage() == null
                    || result.getOutput().getChoices().get(0).getMessage().getContent() == null) {
                System.err.println("AI返回结果异常，尝试直接匹配输入值...");
                return null; // 触发后续的直接匹配逻辑
            }

            String content = result.getOutput().getChoices().get(0).getMessage().getContent()
                    .trim()
                    .replaceAll("[^a-zA-Z0-9]", "");
            return content.isEmpty() ? null : content;

        } catch (Exception e) {
            System.err.println("字段映射失败：" + e.getMessage() + "，尝试直接匹配输入值...");
            return null; // 触发后续的直接匹配逻辑
        }
    }

    /**
     * 提取数值范围（如年订单额、风险等级）
     */
    public String extractNumericRange(String prompt) {
        try {
            GenerationParam param = GenerationParam.builder()
                    .model("qwen-turbo")
                    .messages(Collections.singletonList(
                            Message.builder()
                                    .role(Role.USER.getValue())
                                    .content(prompt)
                                    .build()
                    ))
                    .apiKey(OPENAI_API_KEY)
                    .build();

            Generation generation = new Generation();
            GenerationResult result = generation.call(param);

            if (result == null
                    || result.getOutput() == null
                    || result.getOutput().getChoices() == null
                    || result.getOutput().getChoices().isEmpty()
                    || result.getOutput().getChoices().get(0).getMessage() == null) {
                System.err.println("AI返回结果异常");
                return null;
            }

            return result.getOutput().getChoices().get(0).getMessage().getContent().trim();
        } catch (Exception e) {
            System.err.println("数值提取失败：" + e.getMessage());
            return null;
        }
    }
}